﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using SimpleRssReader.DataSources;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows8Accelerator.Core.Xaml;
using Windows8Accelerator.Core.Xaml.Caching;
using Windows8Accelerator.Core.Xaml.Controls;
using Windows8Accelerator.Core.Xaml.Helpers;
using Windows8Accelerator.Core.Xaml.ViewModels;

namespace SimpleRssReader
{
    sealed partial class App : Application
    {
        public App()
        {
            this.InitializeComponent();
            AppHelperBase.Instance.Initialize();
        }

        protected override async void OnSearchActivated(SearchActivatedEventArgs args)
        {
            await AppHelper.OnSearchActivated(args, typeof(HomePage));
            InitializeSettings();
        }

        private void InitializeSettings()
        {
            SettingsContractHelper.AddSettingsLink("Sobre", AppHelper.CurrentPage, true, new Uri("http://vic.ms/"));
        }

        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            await AppHelper.OnLaunched(args, typeof(HomePage), PreCarregar);
            InitializeSettings();
        }

        private async Task PreCarregar(SuperSplashPageViewModel viewModel)
        {
            viewModel.Text = "Baixando posts mais recentes...";

            var cachedObject = await DataSource.CachedInstance.RetrieveBlogsWithLatestPostsAsync(5);
            if (cachedObject.Origin == ObjectOrigin.Error)
            {
                viewModel.ErrorMessage = "Não estamos conseguindo baixar os posts devido à falta de conectividade com a internet. Por favor, tente novamente mais tarde...";
            }

            if (cachedObject.Origin == ObjectOrigin.RetrievalFunction)
            {
                foreach (var blog in cachedObject.Object)
                {
                    foreach (var post in blog.Posts)
                    {
                        HtmlHelperBase.Instance.PreLoadHtmlImagesAsync(post.Body);
                        await DataSource.CachedInstance.RetrieveFullPostAsync(post);
                    }
                }
            }
        }
    }
}
